<template>
  <el-dialog :model-value="visible" :title="title" width="520px" :fullscreen="mobile" @close="handleClose">
    <el-form :model="form" ref="formRef" label-width="100px">
      <el-form-item
        v-if="type === 'message'"
        prop="phone"
        label="手机号"
        :rules="[
          { required: true, message: '请输入手机号', trigger: 'blur'},
          { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号', trigger: 'blur' }]"
        >
        <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item
        v-if="type === 'email'"
        prop="email"
        label="邮箱"
        :rules="[
          { required: true, message: '请输入邮箱', trigger: 'blur'},
          { type: 'email', message: '请输入正确的邮箱', trigger: 'blur' }]"
        >
        <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item prop="templateId" label="请选择模板" :rules="[{ required: true, message: '请选择模板', trigger: 'change'}]">
        <el-select v-model="form.templateId" placeholder="请选择模板">
          <el-option label="短信模板" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="params" label="预览">
        <el-input type="textarea" v-model="form.params" :rows="5" disabled></el-input>
        <span v-if="type === 'message'">预计产生短信条数：3</span>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleOk">
          发送
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup name="SendMessage">
import useAppStore from '@/store/modules/app'

const { proxy } = getCurrentInstance()

const emit = defineEmits()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  type: {
    type: String,
    default: 'message'
  }
})

const mobile = computed(() => useAppStore().device === 'mobile')
const title = computed(() => {
  if (props.type === 'message') return '发送短信'
  else if (props.type === 'email') return '邮箱发送'
})
const data = reactive({
  form: {
    lockId: undefined,
    email: undefined,
    phone: undefined,
    templateId: undefined,
    params: '"您好，您的开门密码：","输入密码后，按键盘#号键开锁，《无线WIFI密码jy15880500888》"'
  }
})
const { form} = toRefs(data)

watch(() => props.visible, (val) => {
  if (val) resetForm()
})

function resetForm() {
  form.value = {
    lockId: undefined,
    email: undefined,
    phone: undefined,
    templateId: undefined,
    params: '"您好，您的开门密码：","输入密码后，按键盘#号键开锁，《无线WIFI密码jy15880500888》"'
  }
  proxy.resetForm('formRef')
}

function handleClose() {
  emit('cancel')
}
function handleOk() {
  proxy.$refs['formRef'].validate(valid => {
    if (valid) {
      // 将接口内置处理
      emit('ok')
    }
  })
}
</script>
